<!--
  module - 用户与权限--- 用户

  @author wuh 2020-05-07
-->
<template>
  <div>
    <div class="search-bar">
      <div class="base-condition">
        <el-row justify="space-between">
          <el-col :span="12">
            <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal">
              <el-menu-item index="1" @click="queryStatusUserList('')">全部用户</el-menu-item>
              <el-menu-item index="2" @click="queryStatusUserList('locked')">锁定用户</el-menu-item>
              <el-menu-item index="3" @click="queryStatusUserList('normal')">普通用户</el-menu-item>
            </el-menu>
          </el-col>
          <el-col :span="12" style="text-align:right;">
            <el-link type="primary" style="line-height:50px;margin-right:15px;" @click="showF = !showF">更多筛选</el-link>
            <el-input
              v-model="listQuery.phone"
              placeholder="请输入电话"
              class="radius-input"
              style="width: 200px;margin-top:7px;"
              clearable
              @keyup.enter.native="search"
            >
              <i slot="prefix" class="el-input__icon el-icon-search" @click="search" />
            </el-input>
          </el-col>
        </el-row>
      </div>
      <el-collapse-transition>
        <div v-show="showF" class="more-condition">
          <div class="transition-box">
            <el-form ref="form" :model="listQuery" label-width="100px">
              <el-row>
                <el-col :xs="12" :sm="10" :lg="8" :xl="6">
                  <div class="grid-content bg-purple">
                    <el-form-item label="所属部门">
                      <el-cascader
                        ref="dep"
                        v-model="listQuery.depId"
                        :options="options"
                        :props="treeProps1"
                        clearable
                        @change="depChange"
                      />
                    </el-form-item>
                    <el-form-item label="邮箱">
                      <el-input v-model="listQuery.email" placeholder="请输入内容" clearable />
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" @click="search">确认</el-button>
                      <el-button @click="showF = !showF">取消</el-button>
                    </el-form-item>
                  </div>
                </el-col>
                <el-col :span="12" :sm="10" :lg="8" :xl="6">
                  <div class="grid-content bg-purple-light">
                    <el-form-item label="用户名称">
                      <el-input v-model="listQuery.userName" placeholder="请输入内容" clearable />
                    </el-form-item>
                    <el-form-item label="真实姓名">
                      <el-input v-model="listQuery.realName" placeholder="请输入内容" clearable />
                    </el-form-item>
                  </div>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </div>
      </el-collapse-transition>
      <div v-show="showT" class="query-result">
        <span class="filter-title">筛选条件：</span>
        <div
          v-for="(val, key) in listQuery"
          v-show="(key === 'phone' || key === 'depName' || key === 'email' || key === 'userName' || key === 'realName') && val !== ''"
          :key="key"
          class="filter-item"
        >
          <div v-if="key === 'phone'" class="filter-item">
            电话：{{ val }}<i class="el-icon-close" @click="listQuery.phone = '';search()" />
          </div>
          <div v-if="key === 'depName'" class="filter-item">
            部门：{{ val }}<i class="el-icon-close" @click="listQuery.depName = '';search()" />
          </div>
          <div v-if="key === 'email'" class="filter-item">
            邮箱：{{ val }}<i class="el-icon-close" @click="listQuery.email = '';search()" />
          </div>
          <div v-if="key === 'userName'" class="filter-item">
            用户名称：{{ val }}<i class="el-icon-close" @click="listQuery.userName = '';search()" />
          </div>
          <div v-if="key === 'realName'" class="filter-item">
            真实姓名：{{ val }}<i class="el-icon-close" @click="listQuery.realName = '';search()" />
          </div>
        </div>
        <el-button type="text" style="padding:0;margin-left:20px;" @click="clearQuery">清空筛选结果</el-button>
      </div>
    </div>

    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>用户列表<em>（共{{ total }}条记录）</em></span>
        <!-- <el-button v-waves size="middle" type="primary" class="filter-item" style="float: right; margin-left: 10px;" @click="handUpdate(1, '')">
          添加
        </el-button> -->
        <el-link type="primary" class="filter-item" style="float: right; margin-left: 10px;" @click="handUpdate(1, '')">
          添加
        </el-link>
      </div>
      <div>
        <el-row :gutter="20">
          <el-col :span="leftWide">
            <!-- start 列表 -->
            <el-table
              v-loading="listLoading"
              :data="list"
              height="550"
              style="width: 100%"
              :fit="true"
              :header-cell-style="{background:'#eef1f6',color:'#606266'}"
            >
              <el-table-column type="index" width="50" label="#" align="center" />
              <el-table-column label="部门名称" prop="depName" :width="150" :show-overflow-tooltip="true" align="center" />
              <el-table-column label="用户名称" prop="userName" :width="150" :show-overflow-tooltip="true" align="center" />
              <el-table-column label="真实姓名" prop="realName" :width="100" :show-overflow-tooltip="true" align="center" />
              <el-table-column label="手机号" prop="phone" :width="150" :show-overflow-tooltip="true" align="center" />
              <el-table-column label="邮箱" prop="email" :width="300" :show-overflow-tooltip="true" align="center" />
              <el-table-column label="是否锁定" :width="100" :show-overflow-tooltip="true" align="center">
                <template slot-scope="scope">
                  <el-button v-if="scope.row.status == 'normal'" type="info" icon="el-icon-unlock" size="mini" circle @click="handLock(scope.row)" />
                  <el-button v-if="scope.row.status == 'locked'" type="warning" icon="el-icon-lock" size="mini" circle @click="handLock(scope.row)" />
                </template>
              </el-table-column>
              <el-table-column label="最后更新时间" :width="300" :show-overflow-tooltip="true" align="center">
                <template slot-scope="scope">
                  <div>{{ scope.row.lastEditTime|parseTime }}</div>
                </template>
              </el-table-column>
              <el-table-column label="操作" class-name="small-padding fixed-width" fixed="right" :width="250" align="center">
                <template slot-scope="scope">
                  <template>
                    <el-link type="info" size="mini" @click="handUpdate(3, scope.row)">
                      查看
                    </el-link>
                  </template>
                  <template>
                    <el-link type="primary" size="mini" @click="handUpdate(2, scope.row)">
                      修改
                    </el-link>
                  </template>
                  <template>
                    <el-link type="primary" size="mini" @click="setRole(scope.row)">
                      角色分配
                    </el-link>
                  </template>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
          <el-col :span="rightWide">
            <el-card class="box-card" style="margin: 0px;box-shadow: 0px 0px 0px #000">
              <div slot="header" class="clearfix">
                <span>[{{ roleUserName }}]的角色权限</span>
                <el-button
                  v-waves
                  size="mini"
                  type="primary"
                  class="filter-item"
                  style="float: right; margin-left: 10px;"
                  @click="saveUserRole"
                >
                  保存
                </el-button>
              </div>
              <div class="text item">
                <el-tree
                  ref="treeData"
                  :data="roleData"
                  :props="treeProps2"
                  show-checkbox
                  node-key="roleId"
                  @check-change="handleCheckChange"
                />
              </div>
            </el-card>
          </el-col>
        </el-row>
        <el-row type="flex" justify="end" style="margin-top:15px;">
          <!-- start 分页 -->
          <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" style="text-align:right;" @pagination="queryUserList" />
          <!-- end 分页 -->
        </el-row>
      </div>
    </el-card>
  </div>
</template>

<script>
// api
import { queryUserList, lockUser, queryUserRole, saveUserRole } from '@/api/userAndRole/sysUser.js'
import { queryDepartmentList } from '@/api/userAndRole/sysDepartment.js'
import { queryRoleList } from '@/api/userAndRole/sysRightsRole.js'
// 水波纹插件
import waves from '@/directive/waves'
// 分页
import Pagination from '@/components/Pagination'

export default {
  name: 'SysUser',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      activeIndex: '1',
      showF: false,
      showT: false,
      total: 0,
      list: [],
      listLoading: false,
      leftWide: 24,
      rightWide: 0,
      roleUserId: '',
      roleUserName: '',
      listQuery: {
        page: 1,
        limit: 10,
        phone: '',
        depId: [],
        depName: '',
        email: '',
        userName: '',
        realName: '',
        status: ''
      },
      treeProps1: {
        value: 'departmentId',
        label: 'name',
        children: 'children',
        checkStrictly: true
      },
      treeProps2: {
        id: 'roleId',
        label: 'roleName'
      },
      options: [],
      roleData: [],
      roleValue: []
    }
  },
  created() {
    this.queryUserList()
    queryDepartmentList({ multistep: true }).then(res => {
      if (res.code === 1) {
        this.options = res.data.sysDepartmentList
      } else {
        this.noticeUtil.errorMsg('操作失败!')
      }
    })
    const query = {
      page: 1,
      limit: 0,
      treeType: true
    }
    queryRoleList(query).then(res => {
      if (res.code === 1) {
        this.roleData = res.data.roleList
      } else {
        this.noticeUtil.errorMsg('操作失败!')
      }
    })
  },
  methods: {
    queryUserList() {
      const curVue = this
      const query = {
        page: curVue.listQuery.page,
        limit: curVue.listQuery.limit,
        phone: curVue.listQuery.phone,
        departmentId: curVue.listQuery.depId[curVue.listQuery.depId.length - 1],
        email: curVue.listQuery.email,
        userName: curVue.listQuery.userName,
        realName: curVue.listQuery.realName,
        status: curVue.listQuery.status
      }
      queryUserList(query).then(res => {
        if (res.code === 1) {
          curVue.listLoading = false
          curVue.list = res.data.userList
          curVue.total = res.data.totalCount
        } else {
          curVue.noticeUtil.errorMsg('用户获取失败！')
        }
      })
    },
    handLock(data) {
      const curVue = this
      const formObj = {
        userId: data.userId,
        status: ''
      }
      let mes = ''
      if (data.status === 'locked') {
        formObj.status = 'normal'
        mes = '您确定要解锁此用户吗?'
      } else {
        formObj.status = 'locked'
        mes = '您确定要锁定此用户吗?'
      }
      this.noticeUtil.confirm(mes).then(() => {
        lockUser(formObj).then(res => {
          if (res.code === 1) {
            curVue.noticeUtil.successMsg('操作成功！')
            curVue.queryUserList()
          } else {
            curVue.noticeUtil.errorMsg('操作失败!')
          }
        })
      }).catch(() => {
        curVue.noticeUtil.warningMsg('已取消操作！')
      })
    },
    queryStatusUserList(data) {
      this.listQuery.status = data
      this.listQuery.page = 1
      this.queryUserList()
    },
    handUpdate(type, data) {
      this.$router.push({ path: '/userAndRole/updateSysUser', query: { data: data.userId, type: type + '' }})
    },
    setRole(data) {
      const curVue = this
      if (curVue.roleUserId !== data.userId) {
        curVue.roleUserId = data.userId
        curVue.roleUserName = data.userName
        queryUserRole({ userId: curVue.roleUserId }).then(res => {
          if (res.code === 1) {
            curVue.roleValue = res.data.roleList
            curVue.$refs['treeData'].setCheckedKeys(curVue.roleValue)
          } else {
            curVue.noticeUtil.errorMsg('用户角色获取失败！')
          }
        })
        curVue.leftWide = 18
        curVue.rightWide = 6
      } else {
        curVue.roleUserId = ''
        curVue.roleUserName = ''
        curVue.leftWide = 24
        curVue.rightWide = 0
      }
    },
    depChange() {
      const nodesObj = this.$refs['dep'].getCheckedNodes()
      if (nodesObj.length > 0) {
        this.listQuery.depName = nodesObj[0].data.name
      } else {
        this.listQuery.depName = ''
      }
    },
    clearQuery() {
      this.listQuery.depId = []
      this.listQuery.phone = ''
      this.listQuery.depName = ''
      this.listQuery.email = ''
      this.listQuery.userName = ''
      this.listQuery.realName = ''
      this.showT = false
      this.queryUserList()
    },
    search() {
      this.showF = false
      if (this.listQuery.depName.length <= 0) {
        this.listQuery.depId = []
      }
      if (this.listQuery.phone.length > 0 ||
      this.listQuery.depName.length > 0 ||
      this.listQuery.email.length > 0 ||
      this.listQuery.userName.length > 0 ||
      this.listQuery.realName.length > 0) {
        this.showT = true
      } else {
        this.showT = false
      }
      this.queryUserList()
    },
    handleCheckChange(data, checked, indeterminate) {
      const roleId_index = this.arrayIndexOf(data.roleId)
      if (roleId_index >= 0 && !checked) {
        this.roleValue.splice(roleId_index, 1)
      } else if (roleId_index < 0 && checked) {
        this.roleValue.push(data.roleId)
      }
    },
    saveUserRole() {
      const curVue = this
      const formObj = {
        userId: curVue.roleUserId,
        roleIds: curVue.roleValue
      }
      saveUserRole(formObj).then(res => {
        if (res.code === 1) {
          curVue.roleUserId = ''
          curVue.roleUserName = ''
          curVue.leftWide = 24
          curVue.rightWide = 0
          curVue.$refs['treeData'].setCheckedKeys([])
          curVue.noticeUtil.successMsg('操作成功！')
        } else {
          curVue.noticeUtil.errorMsg('保存用户角色失败！')
        }
      })
    },
    arrayIndexOf(val) {
      for (var i = 0; i < this.roleValue.length; i++) {
        if (this.roleValue[i] === val) return i
      }
      return -1
    }
  }
}

</script>

<style lang="scss" scoped>
.search-bar{
  position: relative;
  z-index: 2000;
  width: 100%;
  .base-condition{
    padding: 0 40px;
    background: #fff;
    box-shadow: 0 2px 4px 0 rgba(0,0,0,.14);
    .el-menu-demo,.el-menu-demo *{
      line-height: 50px;
      height: 50px;

      .el-menu-item{
        padding: 0 8px;
        margin-right: 20px;
      }
    }
  }
  .more-condition{
    position: absolute;
    top: 65px;
    background: #fff;
    width: 100%;
    height: auto;
    padding: 20px 40px;
    box-shadow: 0 2px 4px 0 rgba(0,0,0,.14);
  }
  .query-result{
    margin-top: 5px;
    font-size: 12px;
    color: #4c596e;
    padding: 15px 30px;
    background: #fbfdff;
  }
  .query-result *{
    line-height: 25px;
  }
  .filter-item{
    display: inline-block;
    padding: 0 10px;
    margin-left: 10px;
    border-radius: 12px;
    background: #e5e9f2;
    color: #7f8997;
  }
  .filter-item i{
    margin-left: 5px;
    font-weight: 700;
    cursor: pointer;
  }

}
.radius-input >>> input{
  border-radius: 100px !important;
}
</style>
<style scoped>
.radius-input >>> input{
      border-radius: 100px !important;
    }
</style>
